package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectCount;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.dao.TaskDetailsDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskCollectEntity;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskReportInfoVO;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.UserWorkVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private MqttProducer mqttProducer;

    @Autowired
    private TaskDetailsDao taskDetailsDao;

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }


    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId, VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }


    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        //日期+序号

        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key = "lkd.task.code." + date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }

    /**
     * 新增工单
     *
     * @param taskViewModel
     * @return boolean
     */

    private void checkHasTodoTask(TaskViewModel taskViewModel) {
        //判断是否有未完成的工单
        LambdaQueryWrapper<TaskEntity> le = Wrappers.<TaskEntity>lambdaQuery()
                .eq(TaskEntity::getInnerCode, taskViewModel.getInnerCode())
                .eq(TaskEntity::getProductTypeId, taskViewModel.getProductType())
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        if (count(le) > 0) {
            throw new LogicException("工单创建失败，当前售货机有未完成工单!");
        }
    }

    private void checkVmStatusAndTaskType(VmVO info, int productType) {
        //如果innercode不存在 debug会不会出错
        if (info == null) {
            throw new LogicException("售货机不存在!");
        }

        //（1）如果是补货工单，状态不是运营状态，抛出异常
        if (VMSystem.TASK_TYPE_SUPPLY == productType
                && !Objects.equals(info.getVmStatus(), VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("当前售货机未运营!");
        }

        // （2）如果是投放工单，状态为运营，抛出异常
        if (VMSystem.TASK_TYPE_DEPLOY == productType
                && Objects.equals(info.getVmStatus(), VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("当前售货机运营中，无法投放!");
        }
        //（3）如果是撤机工单，状态不是运营状态，抛出异常
        if (VMSystem.TASK_TYPE_REVOKE == productType
                && !Objects.equals(info.getVmStatus(), VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("当前售货机未运营!");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean create(TaskViewModel taskViewModel) {

        //判断是否有未完成的工单
        checkHasTodoTask(taskViewModel);

        VmVO info = vmService.getVMInfo(taskViewModel.getInnerCode());

        //校验售货机状态和工单类型是否匹配
        checkVmStatusAndTaskType(info, taskViewModel.getProductType());

        TaskEntity taskEntity = new TaskEntity();
        //拷贝对象至TaskEntity
        BeanUtils.copyProperties(taskViewModel, taskEntity);
        //设置售货机信息
        taskEntity.setRegionId(info.getRegionId());
        taskEntity.setAddr(info.getNodeAddr());

        //工单类型 1234 字段名不同需要手动拷贝
        taskEntity.setProductTypeId(taskViewModel.getProductType());
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        //生成订单编号
        String taskCode = generateTaskCode();
        //设置订单编号到taskEntity
        taskEntity.setTaskCode(taskCode);

        //设置用户信息
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if (user == null) {
            throw new LogicException("执行人不存在!");
        }
        taskEntity.setUserName(user.getUserName());

        //保存工单
        save(taskEntity);
        //补货工单才需要处理补货详情
        if (VMSystem.TASK_TYPE_SUPPLY == taskViewModel.getProductType()) {
            List<TaskDetailsViewModel> details = taskViewModel.getDetails();
            if (!CollectionUtils.isEmpty(details)) {
                for (TaskDetailsViewModel detail : details) {
                    TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();
                    BeanUtils.copyProperties(detail, taskDetailsEntity);
                    taskDetailsEntity.setTaskId(taskEntity.getTaskId());
                    taskDetailsService.save(taskDetailsEntity);
                }
            }
        }
        //创建工单时给人员工单量进行加1
        changeUserTaskCount(taskEntity.getUserId(), 1);
        return true;
    }

    //修改人员工单量
    private void changeUserTaskCount(Integer userId, int add) {
        //更新redis中的工单量
        UserVO user = userService.getUser(userId);
        //String roleCode = Objects.equals(task.getProductTypeId(), VMSystem.TASK_TYPE_SUPPLY)?"1002":"1003";
        String key = VMSystem.generateUserTaskCount(user.getRoleCode(), user.getRegionId());
        redisTemplate.opsForZSet().incrementScore(key, userId, add);
    }

    @Override
    public boolean accept(TaskEntity task) {
        if (!Objects.equals(task.getTaskStatus(), VMSystem.TASK_STATUS_CREATE)) {
            throw new LogicException("工单状态不是待处理");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);//修改工单状态为进行
        return this.updateById(task);
    }

    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVM) {
        TaskEntity task = this.getById(id);  //查询工单
        if (Objects.equals(task.getTaskStatus(), VMSystem.TASK_STATUS_FINISH) ||
                Objects.equals(task.getTaskStatus(), VMSystem.TASK_STATUS_CANCEL)) {
            throw new LogicException("工单已经结束");
        }

        if (Objects.equals(task.getTaskStatus(), VMSystem.TASK_STATUS_PROGRESS)) {
            changeUserTaskCount(task.getUserId(), -1);
        }

        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        task.setDesc(cancelVM.getDesc());
        return this.updateById(task);
    }

    @Override
    public boolean completeTask(Long id) {
        TaskEntity taskEntity = this.getById(id);
        if (taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("工单已经结束");
        }

        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);//修改工单状态
        this.updateById(taskEntity);

        //修改工单量
        changeUserTaskCount(taskEntity.getUserId(), -1);

        //投放 工单 售货机 未投放 -> 运营
        //撤机 运营 ->未投放
        //维修？
        //补货工单 -> 将货道中库存进行更新
        if (Objects.equals(taskEntity.getProductTypeId(), VMSystem.TASK_TYPE_DEPLOY)
                || Objects.equals(taskEntity.getProductTypeId(), VMSystem.TASK_TYPE_REVOKE)) {
            //发送运维工单消息
            this.noticeOperationTask(taskEntity);
        } else if (Objects.equals(taskEntity.getProductTypeId(), VMSystem.TASK_TYPE_SUPPLY)) {
            this.noticeSupplyTask(taskEntity);
        }
        return true;
    }

    @Override
    public Integer getLeastUser(Long regionId, boolean isReparing) {
        String roleCode = isReparing ? "1003" : "1002";
        String key = VMSystem.generateUserTaskCount(roleCode, regionId);
        Set<Object> range = redisTemplate.opsForZSet().range(key, 0, 0);
        if (CollectionUtils.isEmpty(range)) {
            return null;
        }
        return (Integer) new ArrayList<>(range).get(0);
    }



    //补货消息
    private void noticeSupplyTask(TaskEntity taskEntity) {

        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setInnerCode(taskEntity.getInnerCode());
        ArrayList<SupplyChannel> supplyChannels = new ArrayList<>();
        supplyContract.setSupplyData(supplyChannels);

        List<TaskDetailsEntity> taskDetailsEntities =
                taskDetailsDao.selectList(Wrappers.<TaskDetailsEntity>lambdaQuery()
                        .eq(TaskDetailsEntity::getTaskId, taskEntity.getTaskId()));

        //判断详情为空
        if (CollectionUtils.isEmpty(taskDetailsEntities)) {
            log.info("补货详情为空:taskId{}", taskEntity.getTaskId());
            return;
        }

        for (TaskDetailsEntity taskDetailsEntity : taskDetailsEntities) {
            SupplyChannel supplyChannel = new SupplyChannel();
            supplyChannel.setChannelId(taskDetailsEntity.getChannelCode());
            supplyChannel.setCapacity(taskDetailsEntity.getExpectCapacity());
            supplyContract.getSupplyData().add(supplyChannel);
        }

        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, 2, supplyContract);
        } catch (JsonProcessingException e) {
            throw new LogicException("发送时对象转json失败");
        }
    }

    //运维消息
    public void noticeOperationTask(TaskEntity taskEntity) {
        TaskCompleteContract contract = new TaskCompleteContract();
        contract.setTaskType(taskEntity.getProductTypeId());
        contract.setInnerCode(taskEntity.getInnerCode());
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 2, contract);
        } catch (JsonProcessingException e) {
            throw new LogicException("发送时对象转json失败");
        }
    }


    /**
     * 获取当时工单汇总信息(人员统计头部信息)
     *
     * @return
     */


    @Override
    public List<TaskReportInfoVO> taskReportInfo(String start, String end) {
        //运营
        ArrayList<TaskReportInfoVO> taskReportList = new ArrayList<>();

        TaskReportInfoVO operatorInfoVO = new TaskReportInfoVO();
        int operatorTotal = this.count(Wrappers.<TaskEntity>lambdaQuery()
                .eq(TaskEntity::getProductTypeId, 2)
                .gt(TaskEntity::getUpdateTime, start)
                .lt(TaskEntity::getUpdateTime, end)
        );

        operatorInfoVO.setCompletedTotal(getCount(4, 1, start, end));
        operatorInfoVO.setCancelTotal(getCount(3, 1, start, end));
        operatorInfoVO.setDate(start);
        operatorInfoVO.setProgressTotal(getCount(2, 1, start, end));
        operatorInfoVO.setRepair(false);
        operatorInfoVO.setTotal(operatorTotal);
        operatorInfoVO.setWorkerCount(userService.getOperatorCount());
        taskReportList.add(operatorInfoVO);


        //运维
        TaskReportInfoVO RepairerInfoVO = new TaskReportInfoVO();
        int RepairerTotal = this.count(Wrappers.<TaskEntity>lambdaQuery()
                .in(TaskEntity::getProductTypeId, 1, 3, 4)
                .gt(TaskEntity::getUpdateTime, start)
                .lt(TaskEntity::getUpdateTime, end)
        );
        RepairerInfoVO.setCompletedTotal(getCount(4, 2, start, end));
        RepairerInfoVO.setCancelTotal(getCount(3, 2, start, end));
        RepairerInfoVO.setDate(start);
        RepairerInfoVO.setProgressTotal(getCount(2, 2, start, end));
        RepairerInfoVO.setRepair(true);
        RepairerInfoVO.setTotal(RepairerTotal);
        RepairerInfoVO.setWorkerCount(userService.getRepairerCount());
        taskReportList.add(RepairerInfoVO);
        return taskReportList;
    }

    /**.
     * 统计数量的方法
     * @param taskStatus
     * @param TaskType
     * @param start
     * @param end
     * @return
     */
    private int getCount(int taskStatus, int TaskType, String start, String end) {
        //taskTaskType 1.运营 2.运维
        if (TaskType == 1) {
            return this.count(Wrappers.<TaskEntity>lambdaQuery()
                    .eq(TaskEntity::getProductTypeId, 2)
                    .eq(TaskEntity::getTaskStatus, taskStatus)
                    .gt(TaskEntity::getUpdateTime, start)
                    .lt(TaskEntity::getUpdateTime, end)
            );
        } else {
            return this.count(Wrappers.<TaskEntity>lambdaQuery()
                    .in(TaskEntity::getProductTypeId, 1, 3, 4)
                    .eq(TaskEntity::getTaskStatus, taskStatus)
                    .gt(TaskEntity::getUpdateTime, start)
                    .lt(TaskEntity::getUpdateTime, end)
            );
        }
    }

    /**
     * 工单状态统计
     *
     * @param start
     * @param end
     * @return
     */
    @Override
    public List<TaskCollectEntity> getCollectReport(String start, String end) {
        System.out.println("程序已跑通");
        //TaskReportInfoVO taskReportInfoVO = new TaskReportInfoVO();
        ArrayList<String> dateList = new ArrayList<>();
        //将前端传递的数据转换为LocalDate对象
        LocalDate startDate = LocalDate.parse(start);
        LocalDate endDate = LocalDate.parse(end);
        //获取从start到end期间的每天数
        long distance = ChronoUnit.DAYS.between(startDate, endDate);
        Stream.iterate(startDate, date -> date.plusDays(1))
                .limit(distance + 1)
                .forEach(day -> dateList.add(day.toString()));
        //创建TaskCollectEntity实体对象

        ArrayList<TaskCollectEntity> taskCollectEntitys = new ArrayList<>();
        //遍历每天的工单状态 封装到TaskCollectEntity实体对象中
        for (int i = 0; i < dateList.size() - 1; i++) {
            TaskCollectEntity taskCollectEntity = new TaskCollectEntity();
            //查询每天已完成的工单数
            int finishCount = this.count(Wrappers.<TaskEntity>lambdaQuery()
                    .between(TaskEntity::getUpdateTime, dateList.get(i), dateList.get(i + 1))
                    .eq(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_FINISH));
            //查询每天进行中的工单数
            int processCount = this.count(Wrappers.<TaskEntity>lambdaQuery()
                    .between(TaskEntity::getUpdateTime, dateList.get(i), dateList.get(i + 1))
                    .eq(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS));
            //查询每天取消的工单数
            int cancelCount = this.count(Wrappers.<TaskEntity>lambdaQuery()
                    .between(TaskEntity::getUpdateTime, dateList.get(i), dateList.get(i + 1))
                    .eq(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_CANCEL));
            taskCollectEntity.setFinishCount(finishCount);
            taskCollectEntity.setProgressCount(processCount);
            taskCollectEntity.setCancelCount(cancelCount);
            //设置发生日期
            taskCollectEntity.setCollectDate(LocalDate.parse(dateList.get(i)));
            //封装到集合中
            taskCollectEntitys.add(taskCollectEntity);
        }
        return taskCollectEntitys;
    }


    /**
     * 获取人效排名月度统计排位
     * @param start
     * @param end
     * @param isRepair
     * @param regionId
     * @return
     */
    @Override
    public List<UserWorkVO> getRank(String start, String end, Boolean isRepair, Long regionId) {
        //校验参数
        if(StringUtils.isEmpty(start) || StringUtils.isEmpty(end)
                || isRepair == null || regionId == null){
            throw new LogicException("参数异常");
        }

        //构建器创建sql语句
        QueryWrapper<TaskEntity> taskEntityQueryWrapper = new QueryWrapper<>();

        //时间段内所有满足的完成的工单
        LambdaQueryWrapper<TaskEntity> queryWrapper = taskEntityQueryWrapper
                .select("count(*) count , user_name").lambda()
                //时间区间从start开始到end结束
                .between(TaskEntity::getUpdateTime, start, end)
                //匹配工单状态是否完成
                .eq(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_FINISH)
                //匹配区域
                .eq(regionId != 0,TaskEntity::getRegionId,regionId)
                //根据名字分组
                .groupBy(TaskEntity::getUserName)
                .last(" limit 10");


        //true：运维工单;
        if(isRepair){
            //运维工单(product_type_id不是2)
            queryWrapper.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);

            //false：运营工单
        }else {
            //运营工单(补货工单)(product_type_id是2)
            queryWrapper.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);

        }

        //使用收集器获取满足条件的数据
        List<TaskEntity> list = this.list(queryWrapper);
        //int i = list.get(0).hashCode();

        //结果返回
        List<UserWorkVO> result = new ArrayList<>();

        for (TaskEntity taskEntity : list) {
            //VO实体类
            UserWorkVO userWorkVO = new UserWorkVO();

            userWorkVO.setUserName(taskEntity.getUserName());
            userWorkVO.setWorkCount(taskEntity.getCount());

            result.add(userWorkVO);
        }

        return result;
    }


}
